using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;
using System;

[System.Serializable]
public class SkillBtn
{
	public GameObject btn;
	public GameObject label;
	public GameObject disable;
	public bool isActive;
	public int mp_cost;
	
	public void Disable()
	{
		isActive = false;
		//btn.GetComponent<UISprite>().alpha = 150/255.0f;
		disable.SetActive(true);
		btn.collider.enabled = false;
		//UIButtonScale [] scaleList = btn.GetComponents<UIButtonScale>();
		//foreach( UIButtonScale scale in scaleList)
		//	scale.enabled = false;
	}
	public void Enable()
	{
		isActive = true;
		//btn.GetComponent<UISprite>().alpha = 1.0f;
		disable.SetActive(false);
		btn.collider.enabled = true;
		//UIButtonScale [] scaleList = btn.GetComponents<UIButtonScale>();
		//foreach( UIButtonScale scale in scaleList)
		//	scale.enabled = true;
	}
	public void InitSkillBtn(int cost, string skillName)
	{
		mp_cost = cost;
		btn.SetActive(true);
		Disable();
	}
}

[System.Serializable]
public class ItemBtn
{
	public GameObject btn;
	public GameObject disable;
	public bool isActive;
	public ItemType itemType;
	public void Disable()
	{
		return;
        //isActive = false;
		//disable.SetActive(true);
        //btn.collider.enabled = false;

	}
	public void Enable()
	{
		if(GetItemCount()<=0)
			return;
		isActive = true;
		
		//disable.SetActive(false);
		btn.collider.enabled = true;

	}
	public int GetItemCount()
	{
		return btn.GetComponent<UseItemIcon>().itemCount;
	}
	public void UpdateItemCount(int count)
	{
		return;
        //btn.GetComponent<UseItemIcon>().UpdateItemCount(count);
	}
}


[System.Serializable]
public class Team
{
	public Unit [] unit;
	public string [] unitSpriteNames;
	public int SID;
	public int curMp;
	public int maxMp;	
	public Team()
	{
		unitSpriteNames = new string[5];
		for(int i=0; i< unitSpriteNames.Length; i++)
			unitSpriteNames[i] = "leader_back";
		unit = new Unit[5];
		for(int i=0; i< unit.Length; i++)
		{
			unit[i] = new Unit();
		}		
	}
	
	public bool IsAllUnitHPFull()
	{
		for(int i=0; i< unit.Length; i++)
		{
			if(unit[i].hp < unit[i].maxHp)
				return false;
		}
		return true;
	}	
	
	public bool IsAllUnitAlive()
	{
		for(int i=0; i< unit.Length; i++)
		{
			if(unit[i].isDead)
				return false;
		}
		return true;
	}
	
	public bool IsHPPotionUsable()
	{
		for(int i=0; i< unit.Length; i++)
		{
			if(unit[i].hp < unit[i].maxHp && !unit[i].isDead)
				return true;
		}
		return false;
	}
	
	public bool IsResurrectPotionUsable()
	{
		for(int i=0; i< unit.Length; i++)
		{
			if(unit[i].isDead)
				return true;
		}
		return false;
	}	
	

}

[System.Serializable]
public class Unit
{
	public int hp;
	public int maxHp;
	public bool isDead;
	public int hpChange;
	public int hpToBe;
	public float hpFillAmount;
	public bool isShowHPChageEffect;
}

[System.Serializable]
public class TagPerson
{
	public GameObject nameTag;
	public BoardPerson person;
	public bool isActive;
	public void SetActive(bool bSet)
	{
		isActive = bSet;
		NGUITools.SetActive(nameTag, bSet);
	}
	public void Init(BoardPerson _p, string _nick, int num)
	{
		person = _p;
//		nameTag.GetComponentInChildren<UILabel>().text = _nick;
		if(true)//num==0)
			nameTag.GetComponentInChildren<UISprite>().enabled = false;
		else
		{
			string str = String.Format("IngameUi_{0:00}",num+7);
			nameTag.GetComponentInChildren<UISprite>().spriteName = str;
		}
		nameTag.transform.parent = person.transform;
		nameTag.transform.localPosition = new Vector3(0, _p.overHeadNameTagOffset, 0);
	}
	
	public void SetVisibleTagName(bool isVisible)
	{
//		nameTag.GetComponentInChildren<UILabel>().enabled = isVisible;
	}
	
//	public void SetPosition(MainHUDUI hud)
//	{
//		Vector3 tagPos = person.renderer.bounds.center;
//		glog.debug("setpos "+person.renderer.bounds.center+"  "+person.transform.position+"  "+person.renderer.bounds.extents.y+"   "+person.renderer.bounds.size.y);
//		tagPos.y += person.renderer.bounds.extents.y + 0.05f;
//		Vector2 scrPos = hud.FindScrPos(tagPos);		
//		nameTag.transform.localPosition = new Vector3(scrPos.x, scrPos.y, nameTag.transform.localPosition.z);
//	}
}

public class MainHUDUI : HudUI {
	
	private static MainHUDUI instance;

	public static MainHUDUI Instance{
		get{
			return instance;
		}
	}	

	void Awake()
	{
		instance = this;
		
		for(int i=0; i<playerTag.Length; i++)
		{
			playerTag[i].SetActive(false);
		}		

		ObjectPool.CreatePool(movebonusPrefab);
		
	}	

	public int skillNum;
	public SkillBtn [] skillBtn;
	public int itemNum;
	public ItemBtn [] itemBtn;
	
	public GameObject playerStartPos;
	public GameObject playerEndPos;
	
	public GameObject bossStartPos;
	public GameObject bossEndPos;
	
	public GameObject[] playerTag;
	public GameObject playerTag_2pYellow;
	public GameObject orderTag;
	public GameObject orderTagBack;
//	public TagPerson[] ingameNameTag;
//	public List<TagPerson> ingameNameTag_spawned = new List<TagPerson>();
	//public Vector3 [] destPos;
	
	public List<Team> m_team = new List<Team>();
	public Team myTeam;

	
	public bool bUseHPItem;
	public GameObject iconOverHeadPrefab;
	public GameObject iconSkillOverHeadPrefab;
	public GameObject topLeftAnchor;
	public GameObject trailUnitAttackPrefab;
	public GameObject trailUnitAttack;
	public bool bEffectAttackUnitDone;
	
	//public float markerSpeed = 4.0f;
	
	// Use this for initialization
	void Start () {
		//destPos = new Vector3[playerTag.Length];

//			playerTag[i].transform.position = playerStartPos.transform.position;
//			
//			NGUITools.SetActive(playerTag[i],false);
//			destPos[i] = playerStartPos.transform.position;
//		}
//		RepositionOrderTag();
//		itemBtn[0].UpdateItemCount( MyInfo.Instance.HPPotion);
//		itemBtn[1].UpdateItemCount( MyInfo.Instance.ResurrectPotion);
	}
	
	public void SetPlayerTagStart(int index, bool isBoss)
	{
		if(isBoss)
		{
			index = index-1;
			playerTag[index] = playerTag_2pYellow;
			playerTag[index].SetActive(true);
			playerTag[index].transform.localPosition = bossStartPos.transform.localPosition;
		}
		else
		{
			playerTag[index].SetActive(true);
			playerTag[index].transform.localPosition = playerStartPos.transform.localPosition;
		}
	}
	
	void RepositionOrderTag()
	{
//		Vector3 pos = playerTag[0].transform.localPosition;
//		orderTag.transform.localPosition = new Vector3(orderTag.transform.localPosition.x, pos.y + 10.5f, orderTag.transform.localPosition.z);
//		orderTagBack.transform.localPosition = new Vector3(orderTagBack.transform.localPosition.x, pos.y + 1.5f, orderTagBack.transform.localPosition.z);		
	}
	
	public void ClearTeam()
	{
		m_team.Clear();
	}
	
	public void AddTeam(int sid, bool isMe)
	{
		Team newTeam = new Team();
		newTeam.SID = sid;
		m_team.Add ( newTeam );
		if(isMe) {
			myTeam = newTeam;
			curTeamShowing = myTeam;
			mySID = sid;
//			SetMainCharMP(sid,0);
		}
		
	}
	
	Team GetTeam(int sid)
	{
		foreach( Team team in m_team) {
			if( team.SID == sid)
				return team;
		}
		return null;
	}
		
	public string GetIconName(int sid, int index)
	{
		return GetTeam(sid).unitSpriteNames[index];
	}
	
	public void DecreaseMpBySkill(int skillIndex)
	{
		SetMainCharMP( mySID,skillBtn[skillIndex].mp_cost);
	}
	
	public void DisableSkillBtn()
	{
		return;
        //for(int i=0; i<skillNum; i++)
        //{
			//skillBtn[i].disable.SetActive(true);
			//skillBtn[i].isActive = false;
        //    skillBtn[i].Disable();
        //}
	}
	
	public void EnableSkillBtn()
	{
		return;
        //for( int i=0; i<skillNum; i++)
        //{
        //    if(myTeam.curMp>= skillBtn[i].mp_cost && !myTeam.unit[0].isDead)
        //    {
				//skillBtn[i].disable.SetActive(false);
				//skillBtn[i].isActive = true;
                //skillBtn[i].Enable();
        //    }
        //}
	}

	public void DisableItemBtn()
	{
		for(int i=0; i<itemNum; i++)
		{
			itemBtn[i].Disable();
		}
	}
	
	public void DisableItemBtn1()
	{
		itemBtn[0].Disable();
	}
	
	public void DisableItemBtn2()
	{
		itemBtn[1].Disable();
	}
	
	public void EnableItemBtn()
	{
		if( myTeam.IsHPPotionUsable())
			itemBtn[0].Enable();
		if( myTeam.IsResurrectPotionUsable() )
			itemBtn[1].Enable();
	}	
	
	void CheckDisableItemIcon()
	{
		if(itemBtn[0].GetItemCount()==0 || !myTeam.IsHPPotionUsable())
			itemBtn[0].Disable();
		if(itemBtn[1].GetItemCount()==0 || !myTeam.IsResurrectPotionUsable())
			itemBtn[1].Disable();
	}
	/*
	public void SetActiveTag(int num, BoardPerson person, string nick)
	{
		//ingameNameTag[ num-1].SetActive(true);
		if(num==0)
		{
			TagPerson tagPerson = new TagPerson();
			tagPerson.nameTag = Instantiate( BoardManager.Instance.nameTagPrefab) as GameObject;
			tagPerson.Init(person, nick, num);
			ingameNameTag_spawned.Add ( tagPerson );
			person.tagPerson = tagPerson;
		}
		else
		{
			ingameNameTag[ num-1].nameTag = Instantiate( BoardManager.Instance.nameTagPrefab) as GameObject;
			ingameNameTag[ num-1].Init( person, nick, num);
			NGUITools.SetActive(playerTag[num-1],true);
		}
		
	}*/
	
	public bool MoveMapMarker(int gameOrder, float ratio, float timeTo,bool isBoss, int lapCount)
	{
		//glog.debug("move map marker "+ratio + "  "+lapCount);

		if(gameOrder-1>=playerTag.Length || gameOrder-1<0)
			return false;
		
		Vector3 pos = Vector3.zero;
		
		int index = gameOrder-1;

		if( BoardManager.Instance.curMapRaceType == RaceType.CURCUIT_RACE)
		{
			if(lapCount==-1)
				return false;

			float lapRatio = 1/(float)BoardManager.Instance.lapTotal;
			float modRatio = lapRatio * ( BoardManager.Instance.lapTotal - lapCount) + lapRatio * ratio;
			pos = Vector3.Lerp( playerStartPos.transform.position, playerEndPos.transform.position,  modRatio  );
		}
		else
		{
			if(isBoss) {
				index = index-1;
				pos = Vector3.Lerp(bossStartPos.transform.position, bossEndPos.transform.position, ratio);
			}
			else
				pos = Vector3.Lerp(playerStartPos.transform.position, playerEndPos.transform.position, ratio);

		}

		iTween.MoveTo(playerTag[index], iTween.Hash("position", pos, "easetype", "linear", "time", timeTo) );

		return false;
	}

	public void ChangeMapMarkerByLap(int gameOrder, int lapcount)
	{
		if(gameOrder-1>=playerTag.Length || gameOrder-1<0)
			return;
		int index = gameOrder-1;
		Vector3 pos = Vector3.zero;
		float ratio = 1 - (float)lapcount/(float)BoardManager.Instance.lapTotal;
		pos = Vector3.Lerp(playerStartPos.transform.position, playerEndPos.transform.position, ratio);
		iTween.MoveTo(playerTag[index], iTween.Hash("position", pos, "easetype", "linear", "time", 1.0f) );
	}

	/*
	public void UpdatePlayerToGoalRatio(float ratio, int sid)
	{
		if(sid>0 && sid<=4)
		{
			destPos[sid-1] = Vector3.Lerp(playerStartPos.transform.position, playerEndPos.transform.position, ratio);
			//playerTag[sid-1].transform.position = destPos[sid-1];
		}
	}
	*/	
	
//	IEnumerator WaitForSeatUntaken(int me_index, Vector3 pos)
//	{
//		bool bMarkerOverlapped = true;
//		while(bMarkerOverlapped)
//		{
//			bMarkerOverlapped = false;
//			for(int i=0; i<playerTag.Length; i++)
//			{
//				if(i != me_index)
//				{	
//					float dist_x = playerTag[i].transform.position.x - pos.x;
//					if( Mathf.Abs(dist_x) < 1.1f) {
//						bMarkerOverlapped = true;
//						break;
//					}
//				}
//			}
//			yield return null;
//		}		
//		iTween.MoveTo(playerTag[me_index], iTween.Hash("position", pos, "time",0.2f) );
//	}
//	
//	public Vector3 FindNearPointMarker(int me_index, Vector3 pos, out bool bMarkerOverlapped)
//	{
//		bMarkerOverlapped = true;
//		while(bMarkerOverlapped)
//		{
//			bMarkerOverlapped = false;
//			for(int i=0; i<playerTag.Length; i++)
//			{
//				if(i == me_index)
//					continue;
//				float dist_x = playerTag[i].transform.position.x - pos.x;
//				if( Mathf.Abs(dist_x) < 1.1f) {
//					bMarkerOverlapped = true;
//					if(dist_x>=0)
//						pos.x -= (1.11f - dist_x);
//					else
//						pos.x += (1.11f - dist_x);
//					break;
//				}
//			}
//		}
//
//		return pos;
//	}

	/*
	public void ShowHPEffect(BoardPerson person, bool bShowEffOnPerson)
	{
		int sid = person.SID;
		Team team = GetTeam (sid);
		bool isHPChangeEffectShown = false;
		int nHPChangeType=0;
		bool isRevive = false;
		for(int index=0; index< team.unit.Length; index++)
		{
			if(team.unit[index].hpChange !=0) 
			{
				if(team.unit[index].isShowHPChageEffect) 
				{
					isHPChangeEffectShown = true;
					team.unit[index].isShowHPChageEffect = false;
					if(team.unit[index].hpChange > 0) 
					{
						nHPChangeType = 1;
						
						if(sid==mySID)
						{
							if(team.unit[index].hp<=0)
							{
								MakeLiveUnit(team, index);
								isRevive = true;
							}
							HealUnitEffect(index,team.unit[index].hpChange);
						}
//						else if(sid==EnemyUnitUI.Instance.mySID)
//						{
//							if(team.unit[index].hp<=0)
//							{
//								EnemyUnitUI.Instance.MakeLiveUnit(team, index);
//								isRevive = true;
//							}
//							EnemyUnitUI.Instance.HealUnitEffect(index, team.unit[index].hpChange);
//						}
					}
					else 
					{
						nHPChangeType = 2;
						if(sid==mySID)
							DamageUnitEffect(index,team.unit[index].hpChange);
//						else if(sid==EnemyUnitUI.Instance.mySID)
//							EnemyUnitUI.Instance.DamageUnitEffect(index, team.unit[index].hpChange);
					}
				}
				
				team.unit[index].hp = team.unit[index].hpToBe;//team.unit[index].hp + team.unit[index].hpChange;
				if(team.unit[index].hp<0)
					team.unit[index].hp=0;
				if(team.unit[index].hp>team.unit[index].maxHp)
					team.unit[index].hp = team.unit[index].maxHp;
				team.unit[index].hpChange = 0;
				
				if(sid==mySID) 
					ChangeHPBar(team, index);
//				else if(sid==EnemyUnitUI.Instance.mySID)
//					EnemyUnitUI.Instance.ChangeHPBar(team, index);
			}
		}
		if(isHPChangeEffectShown && bShowEffOnPerson)
		{
			
			Vector3 pos = person.transform.position;
			
			if(nHPChangeType == 1) {
				int nEffectIndex = 3;
				//if(isRevive)
				//	nEffectIndex = 10;
				pos.y += EffectManager.Instance.GetPrefab(nEffectIndex).transform.position.y;
				glog.debug("isHPChangeEffectShown   heal");
				SoundManager.Instance.PlaySound(23);
				GameObject go = EffectManager.Instance.CreateEffect(nEffectIndex, pos);
				go.transform.parent = person.transform;
				//StartCoroutine(StopHpHealEffect(go));
				Destroy(go,3.0f);
			}
			else if(nHPChangeType == 2) {
				pos.z = -3;
				glog.debug("isHPChangeEffectShown   damage");
				GameObject go = EffectManager.Instance.CreateEffect(4, pos);
				go.transform.parent = person.transform;
				Destroy(go,3.0f);
			}
		}
		
		if(sid==mySID)
			CheckDisableItemIcon();
	}*/

	
//	IEnumerator StopHpHealEffect(GameObject go)
//	{
//		yield return new WaitForSeconds(1.0f);
//		go.GetComponent<ParticleSystem>().Stop ();		
//		Destroy(go,2.0f);
//	}	
	
	public void SetUnitSlot(int sid, int index, int unitId, CUnitData unitData, bool isAI, int nAICount)
	{
		Team team = GetTeam (sid);
		if(team!=null)
		{
			string [] unitNames = { "S_os_01","S_er_01","S_sa_01","S_ed_01","S_ed_01" };
			//int i = Random.Range(0, unitNames.Length);
			//glog.debug("unitData.name="+unitData.name);
			if(unitId!=0 && unitData!=null)
				team.unitSpriteNames[index] = unitData.name;
			else if(unitId==0)
				team.unitSpriteNames[index] = "leader_back";
			if(isAI)
				team.unitSpriteNames[index] = unitNames[nAICount];
			//unitImage[index].GetComponent<UISprite>().spriteName = unitSpriteNames[index];//unitData.icon;
			if(sid == mySID)
			{
				unitImage[index].GetComponent<UISprite>().spriteName = team.unitSpriteNames[index];
				unitPanel.SetActive(true);
				SaveOriginalMoveBonusPos(2.0f);
			}
		}
		
	}
	
	public void ShowUnitUI(int sid, BoardPerson person)
	{
//		if(sid != mySID)
//		{
//			EnemyUnitUI.Instance.mySID = sid;
//			EnemyUnitUI.Instance.person = person;
//			EnemyUnitUI.Instance.InitUnit( GetTeam(sid) );
//		}
	}

	public void SetMaxHP(int sid, int index, int maxhp)
	{
		Team team = GetTeam (sid);
		if(team.unit[index].maxHp==0)
			team.unit[index].hp = maxhp;//초기화
		
		team.unit[index].maxHp = maxhp;
		//glog.debug("1maxhp="+team.unit[index].maxHp);
	}
	
	public bool SetChangedHP(int sid, int index, int beforeHp,int deltaHp)
	{
		Team team = GetTeam (sid);
		/*if(team.unit[index].isDead)
		{
			if(hp == team.unit[index].maxHp)
			{
				glog.debug(sid+"  resurrect unit "+index);
				if(sid==mySID)
					MakeLiveUnit(team,index);
				else
					EnemyUnitUI.Instance.MakeLiveUnit(team,index);
			}
			else
				return false;
		}*/
		
		if(deltaHp!=0)
		{
			if(team.unit[index].hp != beforeHp)
			{
				Debug.LogError("client hp differ sever.  "+team.unit[index].hp+"  "+beforeHp);
				
			}
			if(sid== mySID)// || sid == EnemyUnitUI.Instance.mySID)
			{
				glog.debug(sid+" SHOWING unit clienthp="+team.unit[index].hp+"  beforehp="+beforeHp+" deltahp="+deltaHp+"  max="+team.unit[index].maxHp);
				int final_hp = beforeHp + deltaHp;
				if(final_hp<0)
					final_hp = 0;
				if(final_hp>team.unit[index].maxHp)
					final_hp = team.unit[index].maxHp;		
				int valid_delta_hp = final_hp - beforeHp;
				if(valid_delta_hp!=deltaHp)
					glog.debug("recalculated deltahp="+valid_delta_hp);
				if(valid_delta_hp!=0)
				{
					team.unit[index].hpChange = valid_delta_hp;
					team.unit[index].isShowHPChageEffect = true;
					team.unit[index].hpToBe = final_hp;
					return true;
				}
			}
			else
			{
				glog.debug("other unit client hp="+team.unit[index].hp+"  beforehp="+beforeHp+" delta="+deltaHp+"  max="+team.unit[index].maxHp);
				int final_hp = beforeHp + deltaHp;
				if(final_hp<0)
					final_hp = 0;
				if(final_hp>team.unit[index].maxHp)
					final_hp = team.unit[index].maxHp;
				
				if(team.unit[index].hp>0 && final_hp==0)
					team.unit[index].isDead = true;
				team.unit[index].hp = final_hp;
				glog.debug("finalhp="+final_hp);
			}
		}
		return false;

	}
	
	public void SetHP(int sid, int index, int hp)
	{
		Team team = GetTeam (sid);
		if(hp<0)
			hp=0;
		if(hp>team.unit[index].maxHp)
			hp=team.unit[index].maxHp;
		team.unit[index].hp = hp;
		
		if(sid==mySID) 
			ChangeHPBar(team, index);
		//else if(sid==EnemyUnitUI.Instance.mySID)
		//	EnemyUnitUI.Instance.ChangeHPBar(team, index);		
	}
	
	/*
	public bool SetHP(int sid, int index, int hp)
	{
		Team team = GetTeam (sid);
		if(team.unit[index].isDead)
		{
			if(hp == team.unit[index].maxHp)
			{
				glog.debug(sid+"  resurrect unit "+index);
				if(sid==mySID)
					MakeLiveUnit(team,index);
				else
					EnemyUnitUI.Instance.MakeLiveUnit(team,index);
			}
			else
				return false;
		}
		//glog.debug("2maxhp="+team.unit[index].maxHp);
		//float fillAmount = hp/(float)team.unit[index].maxHp;
		//glog.debug("3maxhp="+(float)team.unit[index].maxHp);	
		if(bShowEffect) 
		{
			if( hp != 0 && (sid== mySID || sid == EnemyUnitUI.Instance.mySID) )
			{
				team.unit[index].hpChange = hp;  // delta hp;
				glog.debug(sid+" "+index+" curhp="+team.unit[index].hp+" finalhp="+(team.unit[index].hp + hp)+" deltahp="+hp);
				if(team.unit[index].hp + hp < 0 )
				{
					team.unit[index].hpChange = -team.unit[index].hp;
					glog.debug("recalculated curhp="+team.unit[index].hp+" deltahp="+team.unit[index].hpChange);
				}
				else if( team.unit[index].hp + hp > team.unit[index].maxHp )
				{
					team.unit[index].hpChange = team.unit[index].maxHp - team.unit[index].hp;
					glog.debug("recalculated curhp="+team.unit[index].hp+" deltahp="+team.unit[index].hpChange);
				}
				
				//team.unit[index].hp = team.unit[index].hp + hp;
				
				team.unit[index].isShowHPChageEffect = bShowEffect;
				return true;
			}
		}
		else 
		{
			if(!team.unit[index].isShowHPChageEffect) 
			{// 이펙트 보여주기전까지는 리셋시키지말기
				//team.unit[index].hpChange = hp - team.unit[index].hp;
				team.unit[index].hp = hp;
			}
		}
		return false;
	}*/
	
	public void SetMaxMP(int sid, int _maxmp)
	{
		GetTeam(sid).maxMp = _maxmp;
	}
	
//	IEnumerator SetMP(Team team, UISprite mpSprite, int mp, float fillAmount)
//	{
//		while(Mathf.Abs(mpSprite.fillAmount - fillAmount) > 0.001f )
//		{
//			mpSprite.fillAmount = Mathf.Lerp( mpSprite.fillAmount, fillAmount, Time.deltaTime * 2.0f);
//			yield return null;
//		}
//		team.curMp = mp;
//		MPLabel.GetComponent<UILabel>().text = "MP "+mp.ToString();
//	}	
	
	public void SetMainCharMP(int sid, int mp)
	{
		Team team = GetTeam(sid);
		
		team.curMp = mp;
		
		if(sid==mySID)
			ChangeMPBar(team.curMp, team.maxMp);
		//else if(sid == EnemyUnitUI.Instance.mySID)
		//	EnemyUnitUI.Instance.ChangeMPBar(team.curMp, team.maxMp);

	}

	
	
	public void EffectAttackUnit(Vector3 attackerPos, int sid, int slotIndex)
	{
		Vector3 screenPos = Camera.main.WorldToScreenPoint(attackerPos);
		float x = CSceneManager.widthScreen * screenPos.x/(float)Screen.width;
		float y = CSceneManager.heightScreen * screenPos.y/(float)Screen.height;		
		
		Vector3 destPos = new Vector3();
		if(sid==mySID)
			destPos = unitImage[slotIndex].transform.localPosition;
//		else if(sid == EnemyUnitUI.Instance.mySID)
//		{
//			glog.debug("wid="+CSceneManager.widthScreen+"  height="+CSceneManager.heightScreen);
//			glog.debug("scrwid="+Screen.width+"  height="+Screen.height);
//			glog.debug("x="+x+"  y="+y);
//			float aspect = Screen.width/(float)Screen.height;
//			float our_aspect = (float)CSceneManager.widthScreen/(float)CSceneManager.heightScreen;
//			aspect = our_aspect/aspect;
//			destPos = EnemyUnitUI.Instance.unitImage[slotIndex].transform.localPosition;
//			glog.debug("destPos="+destPos);
//			destPos.x += CSceneManager.widthScreen;
//			destPos.y += CSceneManager.heightScreen;
//			destPos.y *= aspect;
//			//destPos.x = destPos.x * (float)Screen.width/CSceneManager.widthScreen;
//			//destPos.y = destPos.y * (float)Screen.height/CSceneManager.heightScreen;
//		}
		GameObject goEff = NGUITools.AddChild(bottomLeftAnchor, trailUnitAttackPrefab);
		goEff.transform.localPosition = new Vector3(x, y, trailUnitAttackPrefab.transform.position.z );
		
		destPos.z = goEff.transform.localPosition.z;
		glog.debug("EffectAttackUnit localpos = "+goEff.transform.localPosition+ "  "+destPos);
		
		Vector3 midPathVec = goEff.transform.localPosition;
		if(sid==mySID)
		{
			float xsize = goEff.transform.localPosition.x - unitImage[0].transform.localPosition.x;
			float ysize = goEff.transform.localPosition.y - unitImage[0].transform.localPosition.y;
			glog.debug("xsize="+xsize+" ysize="+ysize);
			midPathVec.x -= xsize/4;
			midPathVec.y += ysize/5;
		}
//		else if(sid == EnemyUnitUI.Instance.mySID)
//		{
//			float xsize = goEff.transform.localPosition.x - EnemyUnitUI.Instance.unitImage[0].transform.localPosition.x;
//			float ysize = goEff.transform.localPosition.y - EnemyUnitUI.Instance.unitImage[0].transform.localPosition.y;
//			glog.debug("xsize="+xsize+" ysize="+ysize);
//			midPathVec.x += xsize/4;
//			midPathVec.y -= ysize/5;			
//		}
		// "position", destPos
		Vector3 [] pathList = { goEff.transform.localPosition, midPathVec, destPos };
		// "path", pathList
		iTween.MoveTo( goEff, iTween.Hash("time", 0.5f, "path", pathList,"movetopath",false,  "islocal", true, "easetype","easeInSine" )  );
		bEffectAttackUnitDone = false;
		StartCoroutine(CheckEffectAttackUnitDone(goEff, destPos));
	}
	IEnumerator CheckEffectAttackUnitDone(GameObject goEff, Vector3 destPos)
	{
		while( (goEff.transform.localPosition-destPos).sqrMagnitude>0.01f )
		{
			//glog.debug("goEff.transform.localPosition="+goEff.transform.localPosition);
			//sumTime += Time.deltaTime;
			//trailGo.transform.localPosition = Vector3.Lerp( trailGo.transform.localPosition, destPos, 5*Time.deltaTime);
			yield return null;
		}		
		bEffectAttackUnitDone = true;
		//goEff.GetComponent<ParticleSystem>().Stop();
		Destroy(goEff,1.0f);
	}
	
	GameObject[] rewardAniObjects = new GameObject[4];
	public void ShowItemGetEffect(bool isUnit, BoardPerson person, string itemName, int itemAmount, bool bShowText)
	{
		Debug.Log("ShowItemGetEffect");
		HudManager.Instance.ChangeFace(person.SID, true);
		AchievementCell.DoShowAchieve(person,"obtain");
		if(bShowText)
		{
			string temp = CStringTableManager.Instance.GetItemById(1697);

			if(isUnit)
			{
				temp = temp.Replace("{0}", CStringTableManager.Instance.GetItemById(1878) );
				CardManager.Instance.ShowSkillNameEffect(temp, person.transform);

			}
			else if(itemName=="game_coin")
			{
				temp = temp.Replace("{0}", CStringTableManager.Instance.GetItemById(1112) );
				CardManager.Instance.ShowSkillNameEffect(temp, person.transform);	

			}
			else if(itemName=="cash_coin")
			{
				temp = temp.Replace("{0}", CStringTableManager.Instance.GetItemById(1111) );
				CardManager.Instance.ShowSkillNameEffect(temp, person.transform);	

			}
			else 
			{

				string potionname = "";
				if(itemName=="potion_hp_01")
					potionname = CStringTableManager.Instance.GetItemById(1068);
				else
					potionname = CStringTableManager.Instance.GetItemById(1070);
				temp = temp.Replace("{0}",potionname);
				CardManager.Instance.ShowSkillNameEffect(temp, person.transform);
			}
		}
		Vector3 pos = person.transform.position;
//		pos.y += person.overHeadDiceOffset;
//		pos.z = iconOverHeadPrefab.transform.position.z;

		if(person.curPassingBoard.boardInfo.tilename == BoardInfo.TileName.road_item_01)
		{
			Animator treasureOpenAnim = person.curPassingBoard.gameObject.GetComponentInChildren<Animator>();
			//Vector3 newPos = treasureOpenAnim.transform.localPosition;
			//newPos.y += BoardTile.AddOffsetYForTheme();
			//treasureOpenAnim.transform.localPosition = newPos;
			treasureOpenAnim.enabled=true;
			StartCoroutine(CoTreasureBoxReset(treasureOpenAnim));
			glog.debug("treasure box open");
		}


		if(itemName=="game_coin")
		{
			SoundManager.Instance.PlaySound(26);
			IngameRewardAni obj = LTPrefabManager.InstantiateC(PrefabTypes.RewardCoin, pos, Quaternion.identity) as IngameRewardAni;
			Vector3 originPos = LTPrefabManager.GetPrefabOriginalPosition(PrefabTypes.RewardCoin);
			Vector3 destPos = obj.transform.localPosition;
			//Debug.Log("destPos.y : " + destPos.y);
			//Debug.Log("originPos.y : " + originPos.y);
			destPos.y += originPos.y;
			//Debug.Log("destPos.y : " + destPos.y);
			obj.transform.localPosition = destPos;
			obj.transform.localScale = Vector3.one;
			obj.amountLabel.text = "+" + itemAmount.ToString();

		}
		else if(itemName=="cash_coin")
		{
			SoundManager.Instance.PlaySound(26);
			IngameRewardAni obj = LTPrefabManager.InstantiateC(PrefabTypes.RewardCash, pos, Quaternion.identity) as IngameRewardAni;
			Vector3 originPos = LTPrefabManager.GetPrefabOriginalPosition(PrefabTypes.RewardCash);
			Vector3 destPos = obj.transform.localPosition;
			//Debug.LogError("destPos.y : " + destPos.y);
			//Debug.LogError("originPos.y : " + originPos.y);
			destPos.y += originPos.y;
			//Debug.LogError("destPos.y : " + destPos.y);
			obj.transform.localPosition = destPos;
			obj.transform.localScale = Vector3.one;
			obj.amountLabel.text = "+" + itemAmount.ToString();
		}
		else if(itemName=="potion_hp_01")
		{
			SoundManager.Instance.PlaySound(27);
			GameObject obj = LTPrefabManager.InstantiatePrefab(PrefabTypes.RewardItem, pos, Quaternion.identity);
			Vector3 originPos = LTPrefabManager.GetPrefabOriginalPosition(PrefabTypes.RewardItem);
			Vector3 destPos = obj.transform.localPosition;
			//Debug.LogError("destPos.y : " + destPos.y);
			//Debug.LogError("originPos.y : " + originPos.y);
			destPos.y += originPos.y;
			//Debug.LogError("destPos.y : " + destPos.y);
			obj.transform.localPosition = destPos;
			obj.transform.localScale = Vector3.one;
		}
		else if(itemName=="potion_resurrect_01")
		{
			SoundManager.Instance.PlaySound(27);
			GameObject obj = LTPrefabManager.InstantiatePrefab(PrefabTypes.RewardItem, pos, Quaternion.identity);
			Vector3 originPos = LTPrefabManager.GetPrefabOriginalPosition(PrefabTypes.RewardItem);
			Vector3 destPos = obj.transform.localPosition;
			//Debug.LogError("destPos.y : " + destPos.y);
			//Debug.LogError("originPos.y : " + originPos.y);
			destPos.y += originPos.y;
			//Debug.LogError("destPos.y : " + destPos.y);
			obj.transform.localPosition = destPos;
			obj.transform.localScale = Vector3.one;
		}

		if( isUnit )
		{
			SoundManager.Instance.PlaySound(28);
			GameObject obj = LTPrefabManager.InstantiatePrefab(PrefabTypes.RewardUnit, pos, Quaternion.identity);
			Vector3 originPos = LTPrefabManager.GetPrefabOriginalPosition(PrefabTypes.RewardUnit);
			Vector3 destPos = obj.transform.localPosition;
			//Debug.LogError("destPos.y : " + destPos.y);
			//Debug.LogError("originPos.y : " + originPos.y);
			destPos.y += originPos.y;
			//Debug.LogError("destPos.y : " + destPos.y);
			obj.transform.localPosition = destPos;
			obj.transform.localScale = Vector3.one;
		}
//		GameObject iconObj = Instantiate(iconOverHeadPrefab, pos, Quaternion.identity) as GameObject;
		
//		if(itemName=="game_coin")
//			itemName= "icon_shop_gold_pack_01";
//		else if(itemName=="potion_hp_01")
//			itemName= "icon_shop_potion_hp_pack_01";
//		else if(itemName=="potion_resurrect_01")
//			itemName= "icon_shop_potion_resurrect_pack_01";
//		
//		if(isUnit)
//		{
//			iconObj.transform.FindChild("item").gameObject.SetActive(false);
//			GameObject cardObj = iconObj.transform.FindChild("Card_ingame").gameObject;
//			cardObj.SetActive(true);
//			iconObj.GetComponent<SpriteManipulate>().SetPanelManipulate();
//		}
//		else
//		{
//			iconObj.GetComponent<SpriteManipulate>().SetSpriteName(itemName);
//			iconObj.GetComponent<SpriteManipulate>().ChangeAlphaDelay(0, 2.0f, 1.0f, true);
//		}
//		iTween.MoveTo( iconObj, iTween.Hash("position", new Vector3(pos.x, pos.y + 0.14f, pos.z), "time", 1.0f, "delay", 0.7f,"easetype","linear") );
		
		/*
		itemBtn[0].UpdateItemCount(MyInfo.Instance.HPPotion);
		itemBtn[1].UpdateItemCount(MyInfo.Instance.ResurrectPotion);
		if(itemType == ItemType.HPPotion)
		{
			Vector3 lblPos = itemBtn[0].btn.GetComponent<UseItemIcon>().remainCountLabel.transform.localPosition;
			glog.debug("lblpos="+lblPos);
			GameObject goEff = EffectManager.Instance.NGUICreateEffectZ(5, topLeftAnchor , lblPos);
			Destroy(goEff, 3.0f);
		}
		else if(itemType == ItemType.ResurrectPotion)
		{
			Vector3 lblPos = itemBtn[1].btn.GetComponent<UseItemIcon>().remainCountLabel.transform.localPosition;
			GameObject goEff = EffectManager.Instance.NGUICreateEffectZ(5, topLeftAnchor , lblPos);
			Destroy(goEff, 3.0f);
		}
		*/
	}

	IEnumerator CoTreasureBoxReset(Animator animator)
	{
		yield return new WaitForSeconds(2.0f);
		animator.enabled=false;
		animator.gameObject.SetActive(false);
		//yield return null;
		animator.gameObject.SetActive(true);
	}

	public void ShowSkillIconEffect(BoardPerson person, string iconName)
	{
		//Vector3 pos = person.transform.position;
		//pos.y += person.overHeadDiceOffset;
		//pos.z = iconSkillOverHeadPrefab.transform.position.z;
		
		GameObject iconObj = Instantiate(iconSkillOverHeadPrefab) as GameObject;	
		iconObj.transform.parent = person.transform;
		iconObj.transform.localPosition = new Vector3(0,person.overHeadDiceOffset, iconSkillOverHeadPrefab.transform.position.z);
		iconObj.transform.localScale = iconSkillOverHeadPrefab.transform.localScale;
		iconObj.name = "skillIcon";
		iconObj.GetComponent<SpriteManipulateNew>().SetSpriteName(iconName);
		//iconObj.transform.parent = person.transform;
		//person.skillIconOverHead = iconObj;
		iconObj.GetComponent<SpriteManipulateNew>().ChangeAlphaDelay(0,2.5f,0.7f,true);
		Vector3 newPos = iconObj.transform.localPosition;
		newPos.y += 0.14f;
		LeanTween.moveLocal(iconObj, newPos, 1.0f).setDelay(0.7f);
		//iTween.MoveTo( iconObj, iTween.Hash("position", new Vector3(pos.x, pos.y + 0.14f, pos.z), "time", 1.0f, "delay", 0.7f,"easetype","linear") );		
	}
	
	public void UpdateMoveMapmarker(bool bRankUpdate)
	{
		RepositionOrderTag();
		if(bRankUpdate)
		{
			BoardManager.Instance.boardPersonPCList.Sort(
			    delegate(BoardPerson p1, BoardPerson p2)
			    {
			        return p2.curPassingBoard.boardInfo.pathInfo[p2.mypath].ratioToGoal.CompareTo(p1.curPassingBoard.boardInfo.pathInfo[p1.mypath].ratioToGoal);
			    }
			);		
			for(int i=0; i<BoardManager.Instance.boardPersonPCList.Count; i++)
			{
				if(BoardManager.Instance.boardPersonPCList[i].isMe)
				{
//					orderTag.GetComponent<UISprite>().spriteName = String.Format("IngameUi_{0:00}",i+14);
					break;
				}
			}	
		}
	}

	public int CheckMyRank(int checkIndex)
	{
		float checkX = playerTag[checkIndex].transform.localPosition.x;
		int myRank = 1;
		for(int i=0; i<4; i++)
		{
			if(playerTag[i].activeSelf && i!=checkIndex)
			{
				if(playerTag[i].transform.localPosition.x > checkX)
					myRank++;
			}
		}
		return myRank;
	}
}
